package avaliacao.tagHandler;

import java.io.IOException;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.servlet.jsp.JspException;
import javax.servlet.jsp.JspWriter;
import javax.servlet.jsp.tagext.BodyContent;
import javax.servlet.jsp.tagext.BodyTagSupport;

public class BodyTagHandler extends BodyTagSupport {

    private String handler;
    private String method;
    private String onLoad;
    private String multiPart;
    private String form;
    private boolean isMultiPart;

    /**
     * Creates new instance of tag handler
     */
    public BodyTagHandler() {
        super();
    }

    public String getHandler() {
        return handler;
    }

    public void setHandler(String handler) {
        this.handler = handler;
    }

    public String getMethod() {
        return method;
    }

    public String getForm() {
        return form;
    }

    public void setForm(String form) {
        this.form = form;
    }

    public void setMethod(String method) {
        this.method = method;
    }

    public boolean isIsMultiPart() {
        return isMultiPart;
    }

    public void setIsMultiPart(boolean isMultiPart) {
        this.isMultiPart = isMultiPart;
    }

    public String getOnLoad() {
        return (this.onLoad != null) ? this.onLoad : "";
    }

    public void setOnLoad(String handler) {
        this.onLoad = handler;
    }

    public String getMultiPart() {
        return this.multiPart;
    }

    public void setMultiPart(String multiPart) {
        this.multiPart = multiPart;
        this.isMultiPart = (multiPart != null && multiPart.equals("true"));
    }

    /**
     * Process the body content of the tag.
     * You only need to do this if the tag's BodyContent property
     * is set to "JSP" or "tagdependent."
     */
    private void writeTagBodyContent(JspWriter out, BodyContent bodyContent) throws IOException {
        // write the body content (after processing by the JSP engine) on the output Writer
        bodyContent.writeOut(out);
        // clear the body content for the next time through.
        bodyContent.clearBody();
    }

    /**
     * This method is called when the JSP engine encounters the start tag,
     * after the attributes are processed.
     * Scripting variables (if any) have their values set here.
     * @return EVAL_BODY_BUFFERED if the JSP engine should evaluate the tag body,
     * otherwise return SKIP_BODY.
     */
    @Override
    public int doStartTag() throws JspException {
        JspWriter out = this.pageContext.getOut();

        try {
            out.println("<BODY onLoad=\"" + this.onLoad + "\" class=\"twoColLiqLtHdr\" >");

            out.println("<div id=\"pageContainer\">");
            out.println("<div id=\"header\">");
            out.println("<h1 align=\"center\">Sistema MEC de avalia&ccedil;&atilde;o</h1>");
            out.println("</div>");

            out.println("<div id=\"container\">");

            /* Adiciona <form ... > caso necessário */
            if ((form != null) && form.equals("true")) {
                if (this.handler == null || this.handler.isEmpty()) {
                    throw new JspException("Handler Error");
                }

                if (this.method != null) { //checa se method="post" ou "get"
                    if (this.method.equalsIgnoreCase("post")) {
                        setMethod("POST");
                    } else {
                        setMethod("GET");
                    }
                } else {
                    setMethod("GET");
                }

                if (this.isMultiPart) {
                    out.println(" <FORM ACTION=\"Controller\" NAME=\"meuForm\" METHOD=\""
                            + this.method + "\" "
                            + " ENCTYPE=\"multipart/form-data\" ACCEPT-CHARSET=\"UTF-8\">");
                } else {
                    out.println(" <FORM ACTION=\"Controller\" NAME=\"meuForm\" METHOD=\""
                            + this.method + "\" >");
                }

                out.println("     <INPUT TYPE=\"hidden\" NAME=\"submitbutton\">");
                out.println("     <INPUT TYPE=\"hidden\" NAME=\"pageHandler\" VALUE=\"" + this.handler + "\" />");
            }

        } catch (Exception e) {
            Logger.getLogger(BodyTagHandler.class.getName()).log(Level.SEVERE, e.getMessage());
        }
        return EVAL_BODY_BUFFERED;
    }

    /**
     * This method is called after the JSP engine finished processing the tag.
     * @return EVAL_PAGE if the JSP engine should continue evaluating the JSP page,
     * otherwise return SKIP_PAGE.
     */
    @Override
    public int doEndTag() throws JspException {
        JspWriter out = pageContext.getOut();
        try {
            out.println("        </div>");
            out.println("     </div>");

            /* Fecha </form ... > caso necessário */
            if ((form != null) && form.equals("true")) {
                out.println("  </FORM>");
            }

            out.println("</BODY>");
            out.println("</HTML>");
        } catch (Exception e) {
        }
        return EVAL_PAGE;
    }

    /**
     * This method is called after the JSP engine processes the body content of the tag.
     * @return EVAL_BODY_AGAIN if the JSP engine should evaluate the tag body again,
     * otherwise return SKIP_BODY.
     */
    @Override
    public int doAfterBody() throws JspException {
        try {
            // This code is generated for tags whose bodyContent is "JSP"
            BodyContent bodyCont = getBodyContent();
            JspWriter out = bodyCont.getEnclosingWriter();

            writeTagBodyContent(out, bodyCont);
        } catch (Exception ex) {
            handleBodyContentException(ex);
        }
        return EVAL_PAGE;
    }

    /** Handles exception from processing the body content. */
    private void handleBodyContentException(Exception ex) throws JspException {
        // Since the doAfterBody method is guarded, place exception handing code here.
        throw new JspException("Error in BodyBeforeLogin tag", ex);
    }
}
